package com.qf.controller;

import com.alibaba.fastjson.JSON;
import com.qf.bean.Manager;
import com.qf.bean.RespResult;
import com.qf.common.Const;
import com.qf.common.MybatisUtils;
import com.qf.dao.ManagerDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.ResultSet;

/**
 * projectName:QfeduJava2401
 * author:lcy
 * time:2024/5/8 21:46
 * description:
 */
@WebServlet("/managers")
public class ManagerServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setCharacterEncoding(Const.CHARACTER_ENCODING);
        String method = request.getParameter("method");
        RespResult result=null;
            switch (method){
                case "login":
                    result=login(request,response);
                    break;
                default:
                    break;
            }
            PrintWriter writer =response.getWriter();
            writer.write(JSON.toJSONString(result));
            writer.flush();
            writer.close();
    }

    private RespResult login(HttpServletRequest request, HttpServletResponse response) {
        RespResult result = new RespResult();
        String useraccount = request.getParameter("account");
        String userpwd = request.getParameter("pwd");

        PrintWriter writer=null;
        if (useraccount.length()<4||userpwd.length()<6) {
            try {
                result.setCode(Const.LOGIN_INVALID);
                result.setMsg("参数不合法");
                writer = response.getWriter();
                result.setMsg("参数不合法");
                writer.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        //ManagerDao managerDao =new ManagerDaoImpl();
        ManagerDao managerDao= MybatisUtils.getMapper(ManagerDao.class);
        Manager login = managerDao.login(useraccount, userpwd);
        //提交事务
        MybatisUtils.commit();

        if(login==null){
            result.setCode(Const.LOGIN_FAIL);
            result.setMsg("failed");
        }else{
            result.setCode(Const.LOGIN_SUCCESS);
            result.setMsg("success");

            result.setData(JSON.toJSONString(login));
        }
        //writer.write(JSON.toJSONString(result1));
        //writer.flush();
        //writer.close();
        return result;
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
}


